#include "wx_pch.h"
#include "googleCalendar.h"

struct MemoryStruct
{
    char *memory;
    size_t size;
};

void *myrealloc(void *ptr, size_t size)
{
    /* There might be a realloc() out there that doesn't like reallocing
       NULL pointers, so we take care of it here */
    if (ptr)
        return realloc(ptr, size);
    else
        return malloc(size);
}

size_t WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data)
{
    size_t realsize = size * nmemb;
    struct MemoryStruct *mem = (struct MemoryStruct *)data;

    mem->memory = (char *)myrealloc(mem->memory, mem->size + realsize + 1);
    if (mem->memory)
    {
        memcpy(&(mem->memory[mem->size]), ptr, realsize);
        mem->size += realsize;
        mem->memory[mem->size] = 0;
    }
    return realsize;
}


bool GoogleCalendar::auth(wxString email, wxString passwd)
{
    char* url = "https://www.google.com/accounts/ClientLogin";

    wxString wpost = _T("Email=") + email + _T("&Passwd=") + passwd  + _T("&service=cl");
    char* post = new char[ wpost.length()+1];
    memset(post, 0,  wpost.length()+1);
    wcstombs(post, wpost.c_str(), wpost.length());

    wxString data = getContent(url, "", post);
    if(!data.IsEmpty())
    {
        authToken = data.substr(data.find(_T("Auth="))+5);
    }
    else
    {
        wxMessageBox(_("Login Failed"));
    }
    delete[] post;
    return !data.IsEmpty();
}

wxString GoogleCalendar::getPublicData()
{
    return _T("");
}

wxString GoogleCalendar::getContent(char* url, char* header = "", char* post = "")
{
    CURL *curl;
    CURLcode res;
    struct MemoryStruct chunk;
    chunk.memory=NULL; /* we expect realloc(NULL, size) to work */
    chunk.size = 0;    /* no data at this point */
    curl = curl_easy_init();
    wxString ret;
    if (curl)
    {
        struct curl_slist * slist=NULL;
        slist = curl_slist_append(slist, "Accept-Language: zh_cn");
        if(strlen(header) != 0)
            slist = curl_slist_append(slist, header);

        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &chunk);
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);

        if(strlen(post) != 0)
            curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post);
        res = curl_easy_perform(curl);
        if(res == CURLE_OK)
        {
            int responseCode = -1;
            res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &responseCode);
            if(responseCode == 200) ret = wxString(chunk.memory, wxConvUTF8);
        }
        curl_easy_cleanup(curl);
    }
    return ret;
}

